//
//  EMMApiUtils.m
//  EMMApp
//
//  Created by Mac on 16/5/24.
//  Copyright © 2016年 YiXun. All rights reserved.
//

#import "EMMApiUtils.h"

@implementation EMMApiUtils 
{
    NSString *_method;
    NSString *_body;
    NSInteger _myCacheTimeInSeconds;
}

- (instancetype)initWithMethod:(NSString *)method params:(NSMutableDictionary *)params
{
    self = [super init];
    if (self) {
        _method = method;
        _params = params;
        _myCacheTimeInSeconds = -1;
        
        if (_params != nil) {
            [_params setValue:apiVersion forKey:@"version"];
            [_params setValue:[IDTools devId2] forKey:@"terminalCode"];
            NSDictionary *paramsDict = [NSDictionary dictionaryWithObjectsAndKeys:_params, @"params", nil];
            _body = [paramsDict JSONString];
        }
    }
    return self;
}

- (instancetype)initWithMethod:(NSString *)method params:(NSMutableDictionary *)params cacheTimeInSeconds:(NSInteger)seconds
{
    self = [self initWithMethod:method params:params];
    if (self) {
        _myCacheTimeInSeconds = seconds;
    }
    return self;
}

- (NSString *)requestUrl
{
    return [EMMApiUtils getRequestUrl:_method];
}

- (id)requestArgument
{
    return @{ @"body": _body };
}

- (NSString *)body
{
    return _body;
}

- (NSInteger)myCacheTimeInSeconds
{
    return _myCacheTimeInSeconds;
}

+ (NSString *)getRequestUrl:(NSString *)method
{
    return [NSString stringWithFormat:@"%@/appapi/%@", apiBaseUrl, method];
}

+ (id)respWithSuccess:(NSDictionary *)dict method:(NSString *)method canNewClass:(BOOL)flag
{
    id data = [self respWithSuccess:dict method:method canNewClass:flag baseKey:@"resData"];
    
    if (data == nil) {
        NSLog(@"retry parse.");
        data = [self respWithSuccess:dict method:method canNewClass:flag baseKey:@""];
    }
    
    return data;
}

+ (id)respWithSuccess:(NSDictionary *)dict method:(NSString *)method canNewClass:(BOOL)flag baseKey:(NSString *)baseKey
{
    if (!flag) {
        NSLog(@"response done.");
        return nil;
    }
    
    NSString *json = [IDTools getJson:[dict JSONString] baseKey:baseKey];
    if (json == nil) {
        return nil;
    } else {
        
        NSString *strClass = [method stringWithCapitalizedFirstCharacter];
        
        NSLog(@"////////////////////////////////////////////////////////////////////////////////////////////////////");
        NSLog(@"request Url:\n %@", [EMMApiUtils getRequestUrl:method]);
        NSLog(@"resp result class is :\n%@", strClass);
        NSLog(@"response:\n%@", dict);
        
        NSLog(@"resData --json :\n%@", json);
        NSLog(@"////////////////////////////////////////////////////////////////////////////////////////////////////");
        id myObj = [[NSClassFromString(strClass) alloc] initWithString:json error:nil];
        return myObj;
    }
}

@end
